function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} 
	else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}


function loadCookie() {
	var nombre = getCookie('Campus-Cloud-user_ID');

	if (nombre!=null){
		$("#username").val(nombre);
		$("input#password").get(0).focus();
		$("#password").val("admpass0"); 
	}
	else $("input#username").get(0).focus();
}


function login(){
	
	var username = $("#username").val();
	var password = $("#password").val();
	var remember = $("#checkbox").is(":checked");	

	$.ajax({
                url: "/login",
		type:"POST",
		data: {remember: remember},
		beforeSend : function(req) {
                    req.setRequestHeader("Authorization","Basic " + btoa(username + ":" + password))
                },
                success: mostrarIndex,
                error: mostrarERROR
            });
}

function mostrarIndex(){
	
	window.location.href="/";
}

function mostrarERROR(){
	
	$("#password").val("");	
	$("#Auth_err").css('visibility','visible');	
}

$(document).ready(function(){
	
	loadCookie();	
	
	$("#loginButton").click(function () {
        	login();
    	});
	
	$("input").keydown(function (e){
        	if (e.keyCode == 13) {
            		login();
        	}
    	});
});
